<?php
// bootstrap the console application
require __DIR__.'/../../bootstrap/autoload.php';
$app = require_once __DIR__.'/../../bootstrap/start.php';
$app->setRequestForConsoleEnvironment();
Illuminate\Console\Application::start($app);

use Behat\Behat\Context\ClosuredContextInterface,
    Behat\Behat\Context\TranslatedContextInterface,
    Behat\Behat\Context\BehatContext,
    Behat\Behat\Exception\PendingException;
use Behat\Gherkin\Node\PyStringNode,
    Behat\Gherkin\Node\TableNode;
use Behat\MinkExtension\Context\MinkContext;


//
// Require 3rd-party libraries here:

  // require_once 'PHPUnit/Autoload.php';
  // require_once 'PHPUnit/Framework/Assert/Functions.php';
//

/**
 * Features context.
 */
class FeatureContext extends MinkContext
{

    protected $responseContent = null;

    protected $post;
    
    protected $order;

    /**
     * Initializes context.
     * Every scenario gets its own context object.
     *
     * @param array $parameters context parameters (set them up through behat.yml)
     */
    public function __construct(array $parameters)
    {
        // Initialize your context here
    }

    /**
     * @beforeScenario
     */
    public function startUp() {
    }

    protected function prepareUrl($url) {
        if (strpos($url, "http") === FALSE) {
            return $this->getMinkParameter('base_url') . '/' . $url;
        } else {
            return $url;
        }
    }

    /**
     * @Given /^http "([^"]*)" header is "([^"]*)"$/
     */
    public function httpHeaderIs($arg1, $arg2)
    {
        $this->getSession()->getDriver()->getClient()->setHeader('Accept', 'application/json');
    }

    /**
     * @When /^I make a "([^"]*)" request to "([^"]*)" with:$/
     */
    public function iMakeARequestToWith($method, $url, TableNode $table)
    {
        $data = $table->getHash()[0];
        if (isset($data['group_name']) && $data['group_name'] == 'random_str') {
          $data['group_name'] = 'random_str' . rand(1, 9) . rand(1, 9);
        }
        if (isset($data['title'])) {
            $data['title'] = $data['title'] . $this->genRandomString();
        }
        if (isset($data['content'])) {
            $data['content'] = $data['content'] . $this->genRandomString(36);
        }
        $this->getSession()->getDriver()->getClient()->request(
            'POST', 
            $this->prepareUrl($url), 
            $data
        );
        $this->responseContent = $this->getSession()->getPage()->getContent();
    }

 /**
     * @Given /^I make a "([^"]*)" request to "([^"]*)"$/
     */
    public function iMakeARequestTo($method, $url)
    {
        $this->getSession()->getDriver()->getClient()->request(
            $method, 
            $this->prepareUrl($url)
        );
        $this->responseContent = $this->getSession()->getPage()->getContent();
    }


    /**
     * @Then /^I see "([^"]*)" in the response$/
     */
    public function iSeeInTheResponse($key)
    {
        PHPUnit_Framework_Assert::assertArrayHasKey(
            $key, 
            $this->responseContent, 
            sprintf("response里面没有%s", $key));
    }


    /**
     * @Then /^I see elements in the response:$/
     */
    public function iSeeElementsInTheResponse(TableNode $table)
    {
        foreach($table->getHash() as $row) {
            PHPUnit_Framework_Assert::assertArrayHasKey(
                $row['element_name'], 
                $this->responseContent, 
                sprintf("response里面没有%s", $row['element_name']));
        }
    }

    /**
     * @Given /^I see elements in the response with values:$/
     */
    public function iSeeElementsInTheResponseWithValues(TableNode $table)
    {
        $data = $table->getHash()[0];
        foreach($data as $key => $value) {
            PHPUnit_Framework_Assert::assertEquals(
                (bool)$value, 
                (bool)$this->responseContent['data'][$key], 
                sprintf("response里面的%s和预期的%s不一样", $this->responseContent['data'][$key], $value));
        }
    }

    protected $token=null;

    /**
     * @Given /^http "([^"]*)" header exists$/
     */
    public function httpHeaderExists($authHeader)
    {
        $this->token=$this->responseContent['token'];
        $this->getSession()->setRequestHeader($authHeader, sprintf('bearer %s', $this->token));
    }

    /**
     * @Then /^I see error for "([^"]*)" field "([^"]*)"$/
     */
    public function iSeeErrorForField($field, $error)
    {
        if (!isset($this->responseContent['error_messages']) || !isset($this->responseContent['error_messages']['password'])) {
            throw new Exception(sprintf('没有找到%s的error: %s', $field, $error));
        }
        
        PHPUnit_Framework_Assert::assertEquals(
            $this->responseContent['error_messages']['password'], 
            array($error), 
            sprintf('%s的error是："%s"， 预期是"%s"', $field, $this->responseContent['error_messages']['password'][0], $error));
    }

    /**
     * @Given /^a user exists with:$/
     */
    public function aUserExistsWith(TableNode $table)
    {
        $username = null;
        $password = null;
        foreach($table->getHash() as $row) {
            $username = $row['username'];
            $password = $row['password'];
        }

        try {
            $user = User::where ( 'phone', $username )->firstOrFail ();
        } catch(Exception $ex) {
            Log::error($ex);
            $user = new User ();
            $user->phone = $username;
            $user->account = $username;
            $user->score = 0;
            $user->likes_count = 0;
            $user->collects_count = 0;
            $user->active = 0;
            $user->indie = 1;
            $user->save ();
           // $user->invitor = $uid;
            $user->user_group_id = 1;
            $group = UserGroup::where ( 'id', $user->user_group_id )->firstOrFail ();
            $model_name = $group->model;
            $user_model = new $model_name ();
            $user_model->user_id = $user->id;
            $user_model->save ();
            $user->active = 1;
        }

        $user->password = $password;
        $user->save ();
    }
 /**
     * @Then /^the response is in "([^"]*)" format$/
     */
    public function theResponseIsInFormat($format)
    {
        switch($format) {
            case 'json':
              $response = $this->getSession()->getPage()->getContent();
              // Response::json引入了一些扩展ASCII码，要清除
              $processed = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $response);
              PHPUnit_Framework_Assert::assertJson($processed, sprintf("response不是%s格式", $format));
               $this->responseContent = json_decode($processed, true);
            break;
          }
    }

     /**
     * @Given /^there are "([^"]*)" records$/
     */
    public function thereAreRecords($arg1)
    {
        if (count($this->responseContent['data']) != $arg1) {
            throw new Exception(sprintf("得到的记录数是%s, 而不是%s", count($this->responseContent), $arg1));
        }
    }

     /**
     * @Given /^each "([^"]*)" record contains:$/
     */
    public function eachRecordContains($arg1, TableNode $table)
    {
        $record = array_pop($this->responseContent['data']);
        $hash = $table->getHash();
        foreach ($hash as $row) {
            if (!isset($record[$row['keys']])) {
                throw new Exception(sprintf("验证记录数据失败，没有这个key: %s", $row['keys']));
            }
        }
    }

    /**
     * @Given /^the records are ordered by "([^"]*)" in "([^"]*)"$/
     */
    public function theRecordsAreOrderedByIn($arg1, $arg2)
    {
        $biggest = 1000000000000;
        $dataArr = $this->responseContent['data'];
        foreach($dataArr as $item) {
            if ($biggest < strtotime($item[$arg1])) {
                throw new Exception(sprintf("测试没有通过，因为结果不是按%s的%s排序", $arg1,$arg2));
            } else {
                $biggest = strtotime($item[$arg1]);
            }
        }
    }

  /**
     * @Given /^the records are order by "([^"]*)" in "([^"]*)"$/
     */
    public function theRecordsAreOrderByIn($arg1, $arg2)
    {
        $little = 0;
        $dataArr = $this->responseContent['data'];
        foreach($dataArr as $item) {
            if ($little > strtotime($item[$arg1])) {
                throw new Exception(sprintf("测试没有通过，因为结果不是按%s的%s排序", $arg1,$arg2));
            } else {
                $little = strtotime($item[$arg1]);
            }
        }
    }




     /**
     * @Given /^I am in a directory "([^"]*)"$/
     */
    public function iAmInADirectory($arg1)
    {
        if (!file_exists($arg1)) {
            mkdir($arg1);
        }
        chdir($arg1);
    }

 /**
     * @Given /^I have a file named "([^"]*)"$/
     */
    public function iHaveAFileNamed($arg1)
    {
        touch($arg1);
    }

/**
     * @When /^I run "([^"]*)"$/
     */
    public function iRun($arg1)
    {
       exec($arg1, $output);
        $this->output = trim(implode("\n", $output));
    }

 /**
     * @Then /^I should get:$/
     */
    public function iShouldGet(PyStringNode $string)
    {
        if ((string) $string !== $this->output) {
            throw new Exception(
                "Actual output is:\n" . $this->output
            );
        }
    }

     /**
     * @Then /^I should not get:$/
     */
    public function iShouldNotGet(PyStringNode $string)
    {
        if ((string) $string === $this->output) {
            throw new Exception(
                "Actual output is:\n" . $this->output
            );
        }
    }

    /**
     * @Given /^I got error message "([^"]*)" for field "([^"]*)"$/
     */
    public function iGotErrorMessageForField($message, $field)
    {
        PHPUnit_Framework_Assert::assertArrayHasKey(
            $field, 
            $this->responseContent['error_messages']
        );

        $actualMessage = array_pop($this->responseContent['error_messages'][$field]);
        PHPUnit_Framework_Assert::assertEquals($message, $actualMessage);
    }

    /**
     * @Given /^I can not see error message "([^"]*)" for field "([^"]*)"$/
     */
    public function iCanNotSeeErrorMessageForField($message, $field)
    {
        if (isset($this->responseContent['error_messages'][$field])) {
          $actualMessage = array_pop($this->responseContent['error_messages'][$field]);
          PHPUnit_Framework_Assert::assertNotEquals($message, $actualMessage);
        }
    }
  
  /**
     * @Given /^I get message "([^"]*)" for field "([^"]*)"$/
     */
    public function iGetMessageForField($message,$field)
    {
        $this->responseContent = $this->getSession()->getPage()->getContent();
        $jsonResponse = json_decode($this->responseContent, true);
        //PHPUnit_Framework_Assert::assertEquals(10, sizeof($jsonResponse['data']));
        foreach($jsonResponse['data'] as $record) {
            $actualMessage = $record[$field];
            PHPUnit_Framework_Assert::assertEquals($message, $actualMessage);
        }
    }

   /**
     * @Given /^I gets message "([^"]*)" for field "([^"]*)"$/
     */
    public function iGetsMessageForField($message, $field)
    {
        $this->responseContent = $this->getSession()->getPage()->getContent();
        $jsonResponse = json_decode($this->responseContent, true);
        $actualMessage = array_pop($jsonResponse['data']['comments'][$field]);
        PHPUnit_Framework_Assert::assertEquals($message, $actualMessage);
    }





    // 证明数组是按照follows_count倒序排列
    // public function test() {
    //     $biggest = null;
    //     foreach($array as $data) {
    //         if (is_null($biggest)) {
    //             $biggest = $data['follows_count'];
    //         } else {
    //             if (!$biggest < $data['follows_count']) {
    //                 throw new Exception();
    //             }
    //             $biggest = $data['follows_count'];
    //         }

    //     }
    // }

 /**
     * @Given /^I got message "([^"]*)" for field "([^"]*)"$/
     */
    public function iGotMessageForField($message, $field)
    {
        /*PHPUnit_Framework_Assert::assertArrayHasKey(
            $field, 
            $_REQUEST[$field]
        );
        published=0;*/
        //echo $_GET["$field"]
        //$actualMessage = $_GET["$field"];
        $url=$this->getSession()->getCurrentUrl();
        $rows=parse_url($url); 
        $actualMessage=$rows[$field];
        PHPUnit_Framework_Assert::assertEquals($message, $actualMessage);
    }

    /**
     * @Given /^I see error message "([^"]*)" for field "([^"]*)"$/
     */
    public function iSeeErrorMessageForField($message,$field)
    {
        $actualMessage = $this->responseContent[$field];
        PHPUnit_Framework_Assert::assertEquals($message, $actualMessage);
    }

  /**
     * @Given /^show each "([^"]*)" record  "([^"]*)"$/
     */
    public function showEachRecord($data1)
    {
        //$data1=$this->getResponseContent()['data'];
        $data1 = $this->getResponseContent();
        $data1 = json_decode($data1, true);
        $this->lawyer1 = $data1['data'];
    }
    
    /**
     * @Then /^show each "([^"]*)" record "([^"]*)"$/
     */
    public function showEachRecord2($data2)
    {
        //$data2=$this->getResponseContent()['data'];
        //$data2=$this->getResponseContent()['data'];
        $data2 = $this->getResponseContent();
        $data2 = json_decode($data2, true);
        $this->lawyer2 = $data2['data'];
    }

  /**
     * @Given /^"([^"]*)" equals "([^"]*)"$/
     */
    public function equals($data1, $data2)
    {
        // if($this->lawyer1===$this->lawyer2){
        //     printf("咨询列表的默认排序方式是创建时间的倒序排列");
        // }else{
        //     printf("咨询列表的默认排序方式不是创建时间的倒序排列");
        // }
        
     PHPUnit_Framework_Assert::assertEquals($this->lawyer1, $this->lawyer2);

    }

 /**
     * @Given /^I got success message "([^"]*)" for field "([^"]*)"$/
     */
    public function iGotSuccessMessageForField($message,$field)
    {
        $actualMessage = array_pop($this->responseContent[$field]);
        PHPUnit_Framework_Assert::assertEquals($message, $actualMessage);
    }
 /**
     * @Given /^I see message "([^"]*)" for field "([^"]*)"$/
     */
    public function iSeeMessageForField($message,$field)
    {
        $actualMessage = $this->responseContent['data'][$field];
        PHPUnit_Framework_Assert::assertEquals($message, $actualMessage);
    }

 /**
     * @Given /^a lawyer "([^"]*)" exists with:$/
     */
    public function aLawyerExistsWith2($id, TableNode $table)
    {
        $row = $data = $table->getHash()[0];
        $user = User::find($id);
        User::addLawyerIfNotExist($user);
        $user->load('lawyer');
        // 更新律师的introduce信息
        foreach($row as $key => $value) {
            $user->lawyer->$key = $value;
        }
        // $user->is_verified = true;
        // $user->lawyer->introduce = $value;
        $user->save();
        $user->lawyer->save();
    }

    /**
     * @Given /^a lawyer exists with:$/
     */
    public function aLawyerExistsWith(TableNode $table)
    {
        $row = $data = $table->getHash()[0];
        $user = User::getByUsername($row['username']);
        $lawyerInfo =  array(
            'realname' => 'test lawyer',
            'sex' => 'test lawyer',
            'province' => 'test lawyer',
            'city' => 'test lawyer',
            'district' => 'test lawyer',
            'address' => 'test lawyer',
            'avatar' => 'img/dfimg.png',
            'license' => 'test license',
            'license_file' => 'test license_file',
            'ID_img' => 'test id img',
            'bg_image' => 'img/dfimg.png',
            'company_name' => 'test company name',
            'position' => 'test position',
            'text_reply_fee' => '10',
            'phone_reply_fee' => '20'
        );
        if (!$user) {
            $user = User::addUser($row ['username'], $row ['password'], 'phone', 1);
            //$user = User::addUser($post ['username'], $post ['password'], $post ['account_type'], 1);     // 创建用户
            $user = User::addLawyer($user->id, $lawyerInfo);
        } else if (!$user->isVerifiedLawyer()) {
            $user = User::addLawyer($user->id, $lawyerInfo);
        }
        // 更新律师的introduce信息
        // foreach($row as $key => $value) {
        //     $lawyer->$key = $value;
        // }
        //$this->printDebug(get_class($lawyer));
        //$user = User::find($id);
        //$user->load('lawyer');
        if (isset($row ['username'])) {
            $user->phone = $row['username'];
            $user->account_type_id = 1;
            $user->account = $row['username'];
        }
        if (isset($row ['password'])) {
            $user->setPasswordAttribute ( $row ['password'] );
            $user->reset_time = time ();
        }
        $user->is_verified = true;
        $user->load('lawyer');
        $user->lawyer->save();
        $user->save();
        $this->lawyer = $user;
    }

/**
     * @Given /^this lawyer is a member of group "([^"]*)"$/
     */
    public function thisLawyerIsAMemberOfGroup($group_id)
    {
        $sns_group = SNSGroup::find($group_id);
        $sns_group_member = SNSGroupMember::where('group_id', $group_id)
          ->where('user_id', $this->lawyer->id)
          ->first();
        if (!$sns_group_member) {
          SNSGroupMember::addGroupMember($group_id, $this->lawyer->id);
        }
    }



    /**
     * @Given /^this lawyer is not a member of group "([^"]*)"$/
     */
    public function thisLawyerIsNotAMemberOfGroup($group_id)
    {
        $sns_group = SNSGroup::find($group_id);
        $sns_group_member = SNSGroupMember::where('group_id', $group_id)
          ->where('user_id', $this->lawyer->id)
          ->first();
        if ($sns_group_member) {
            $sns_group_member->delete();
            $sns_group->decrement('lawyers_cnt');
            $sns_group->save();
        }
    }

    /**
     * @Given /^a normal user "([^"]*)" exists with:$/
     */
    public function aNormalUserExistsWith($user_id, TableNode $table)
    {
        $user = User::find ( $user_id );
        $row = $data = $table->getHash()[0];
        if (!$user) {
            $user = User::addUser($row ['username'], $row ['password'], 'phone', 1);
        } else {
            $user->user_group_id = 1;
            $user->is_verified = false;
            $user->save();
        }
    }

    /**
     * @Given /^a users "([^"]*)" exists with:$/
     */
    public function aUsersExistsWith($id, TableNode $table)
    {
        $user = User::find ( $id );
        $row = $data = $table->getHash()[0];
        foreach($row as $key => $value) {
            $user->$key = $value;
        }
        $this->printDebug(get_class($user));
        $user->save();
    }


    protected function getResponseContent() 
    {
        return $this->getSession()->getPage()->getContent();
    }

   /**
     * @Given /^the number of records is "([^"]*)"$/
     */
   /* public function theNumberOfRecordsIs($arg1)
    {
        if (count($this->responseContent['data']) = $arg1) {
            throw new Exception(sprintf("得到的记录数是%s, ",  count($this->responseContent['data'])));
        }
    }

       /**
     * @Given /^the number of records is (\d+)$/
     */



    /**
     * @Given /^valid phone code "([^"]*)" for phone number "([^"]*)"$/
     */
    public function validPhoneCodeForMobile($phoneCode, $phoneNumber)
    {
        $activation = Activation::firstOrNew ( array (
            'mobile' => $phoneNumber
        ) );
        $activation->token = $phoneCode;
        $activation->expired = time () + 3600;
        $activation->save ();
    }

    /**
     * @Given /^user with phone "([^"]*)" does not exist$/
     */
    public function userWithPhoneDoesNotExist($phone)
    {
        $user = User::where ( 'phone', $phone );
        if ($user) {
            $user->delete();
        }
    }
     /**
     * @Given /^user with email "([^"]*)" does not exist$/
     */
    public function userWithEmailDoesNotExist($email)
    {
        $user = null;
        try {
            $user = User::where ( 'email', $email )->firstOrFail();
        } catch(Exception $e) {
            $this->printDebug($e->getMessage());
        }
        if ($user) {
            $this->printDebug("....");
            $user->delete();
        }
    }

    protected $lawyer = null;

    /**
     * @Given /^I save no "([^"]*)" lawyer in record$/
     */
    public function iSaveNoLawyerInRecord($num)
    {
        $content = $this->getResponseContent();
        $content = json_decode($content, true);
        $this->lawyer = $content['data'][$num];
    }

    /**
     * @Given /^the no "([^"]*)" lawyer matches the record$/
     */
    public function theNoLawyerMatchesTheRecord($num)
    {
        $content = $this->getResponseContent();
        $content = json_decode($content, true);
        PHPUnit_Framework_Assert::assertEquals($this->lawyer , $content['data'][$num]);
    }

    /**
     * @Given /^basic auth header exists with credentials:$/
     */
    public function basicAuthHeaderExistsWithCredentials(TableNode $table)
    {
        $row = $data = $table->getHash()[0];
        $username = $row['username'];
        $password = $row['password'];
        $this->getSession()->setRequestHeader(
            'Authorization', 
            sprintf("basic %s", base64_encode($username . ":" . $password))
        );
    }

    /**
     * @Given /^there is a "([^"]*)" request with status "([^"]*)"$/
     */
    public function thereIsARequestWithStatus($type, $status)
    {
        if ($status == Post::STATUS_WAIT_PAY && $type == Post::TYPE_PAY_TEXT) {
            $this->createSampleRequest($type);
        }
        
        if ($status == Post::STATUS_NEW && $type == Post::TYPE_PAY_TEXT) {
            $this->createSampleRequest($type);
            $this->post->status = Post::STATUS_NEW;
            $this->order->state = Order::STATE_PAID;
            $this->order->pay_status = 1;
            $this->post->save();
            $this->order->save();
        }
        
        if ($status == Post::STATUS_NEW && $type == Post::TYPE_QUESTION) {
            $this->createSampleRequest($type);
        }
        
        if ($status == Post::STATUS_REPLIED) {
            // 新咨询
            $this->createSampleRequest($type);
            // 律师抢单
            $this->lawyerTakesRequest();
        }
        
        if ($status == Post::STATUS_COMPLETE) {
            // 新咨询
            $this->createSampleRequest($type);
            // 律师抢单
            $this->lawyerTakesRequest();
            // 用户确定
            $this->userCompletesRequest();
            // 用户评价咨询
            $this->userEvaluatesRequest();
        }
    }

    /**
     * @Given /^there is a request with category "([^"]*)"$/
     */
    public function thereIsARequestWithCategory($category)
    {
        $this->post->post_category = $category;
        $this->post->save();
    }
    
    protected function userCompletesRequest() {
		$credentials = array (
			'phone' => '13702325511',
			'password' => '123456'
		);
        Auth::attempt ( $credentials, false );
		$this->post->status = Post::STATUS_WAIT_FOR_EVALUATION;
		$this->post->save();
    }
    
    protected function userEvaluatesRequest() {
		$credentials = array (
			'phone' => '13702325511',
			'password' => '123456'
		);
        Auth::attempt ( $credentials, false );
		$this->post->status = Post::STATUS_COMPLETE;
		$this->post->save();
		Evaluate::addEvaluation($this->post, 2, 'this is a good request');
    }
    
    protected function lawyerTakesRequest() {
		$credentials = array (
			'phone' => '13702325512',
			'password' => '123456'
		);
		Auth::attempt ( $credentials, false );
		$this->post->status = Post::STATUS_REPLIED;
		$this->post->save();
		$this->post->assignToLawyer(Auth::user()->id);
    }
    
    protected function createSampleRequest($type) {
		$credentials = array (
			'phone' => '13702325511',
			'password' => '123456'
		);
        Auth::attempt ( $credentials, false );
        $postData['post_category'] = 322;
        $postData['title'] = '离婚财产咨询' . $this->genRandomString();
        $postData['content'] = '您好，我和前夫离婚有4年了，离婚协议上房产归我，我补偿35万给他，他搬离。' . $this->genRandomString(36);
        $postData['type'] = $type;
        UserScoresHistory::post();
        
        if ($type == Post::TYPE_PAY_TEXT) {
            $this->post = Post::storePayQuestion($postData);
            $lawyer_id = 22;
            $lawyer = Lawyer::find($lawyer_id);
            $price = '';
            if ($this->post->type == Post::TYPE_PAY_TEXT) {
                $price = $lawyer->text_reply_fee;
            }
            if ($this->post->type == Post::TYPE_PAY_PHONE) {
                $price = $lawyer->phone_reply_fee;
            }
            $order = new Order();
            $order->user_id = Auth::user()->id;
            $order->price = $price;
            $order->title = $postData['title'];
            $order->phone = isset($postData['phone']) ? $postData['phone'] : Auth::user()->phone;
            $order->qty = 1;
            $order->workflow_id = 0;
            $order->state = Order::STATE_INIT;
            $order->pay_status = 0;
            $order->save();
            $this->order = $order;
            $this->post->assignToLawyer($lawyer->user_id);
            $this->post->assignToOrder($order->id);
        } else {
            $this->post = Post::storeQuestion($postData);
        }
    }

    protected function genRandomString($length=16)
    {
        $chars ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";//length:36
        $final_rand='';
        for($i=0;$i<$length; $i++)
        {
            $final_rand .= $chars[ rand(0,strlen($chars)-1)];
    
        }
        return $final_rand;
    }
    
    /**
     * @Given /^I "([^"]*)" this request with route "([^"]*)"$/
     */
    public function iThisRequestWithRoute($action, $routeName)
    {
        $url = route($routeName, $this->post->id);
        $method = 'post';
        if (in_array($action, ['ask', 'view'])) {
            $method = 'get';
        }
        $this->iMakeARequestTo($method, $url);
    }
    
    /**
     * @Given /^I "([^"]*)" this request with route "([^"]*)" and query "([^"]*)"$/
     */
    public function iThisRequestWithRouteAndQuery($action, $routeName, $paramStr)
    {
        $url = route($routeName) . "?" . $paramStr;
        $method = 'post';
        if (in_array($action, ['ask', 'view'])) {
            $method = 'get';
        }
        $this->iMakeARequestTo($method, $url);
    }

    /**
     * @Given /^the status of the request is "([^"]*)"$/
     */
    public function theStatusOfTheRequestIs($status)
    {
        $post = Post::find($this->post->id);
        if ($status != $post->status) {
            throw new Exception(
                sprintf(
                    "The actual status, '%s', is different from the expected one, '%s'.", 
                    $this->post->status, $status
                )
            );
        }
    }    
    
    /**
     * @Given /^I see fields in the response:$/
     */
    public function iSeeFieldsInTheResponse(TableNode $table)
    {
        foreach($table->getHash() as $row) {
            PHPUnit_Framework_Assert::assertArrayHasKey(
                $row['fields'], 
                $this->responseContent['data'], 
                sprintf("response里面没有%s", $row['fields']));
        }
    }    
    
    /**
     * @Given /^lawyer with phone "([^"]*)" has workscope "([^"]*)"$/
     */
    public function lawyerWithUsernameHasWorkscope($phone, $workscope)
    {
        $user = User::where('phone', $phone)->first();
        $lawyer = Lawyer::where('user_id', $user->id)->first();
        $lawyer->work_scope = $workscope;
        $lawyer->save();
    }    
    
    /**
     * @Given /^the "([^"]*)" request with status "([^"]*)" is in the first place of the list$/
     */
    public function theRequestWithStatusIsInTheResponse($type, $status)
    {
        $request = $this->responseContent['data'][0];
        PHPUnit_Framework_Assert::assertEquals($status, $request['status']);
        PHPUnit_Framework_Assert::assertEquals($this->post->id, $request['id']);
        PHPUnit_Framework_Assert::assertEquals($this->post->title, $request['title']);
        
        if ($type == Post::TYPE_PAY_TEXT) {
            PHPUnit_Framework_Assert::assertEquals($this->order->price, $request['price']);
            PHPUnit_Framework_Assert::assertEquals($this->order->qty, $request['qty']);
            PHPUnit_Framework_Assert::assertEquals($this->order->order_no, $request['order_no']);
        }
        
        if ($type == Post::TYPE_QUESTION) {
            PHPUnit_Framework_Assert::assertEquals($this->post->content, $request['content']);
        }
    }
}
